local extension = Package("rfenghou_3dnj")
extension.extensionName = "aaa_fenghou"

local U = require "packages/utility/utility"
local RUtil = require "packages/aaa_fenghou/utility/rfenghou_util"
local DIY = require "packages/diy_utility/diy_utility"

Fk:loadTranslationTable{
  ["rfenghou_3dnj"] = "3D吧赛",
  ["rfenghou_3d9j"] = "3D9J",
  ["rfenghou_3d10j"] = "3D10J",
  ["rfenghou_3d12j"] = "3D12J",
  ["rfenghou_3d13j"] = "3D13J",
  ["rfenghou_3d14j"] = "3D14J",
  ["rfenghou_3d15j"] = "3D15J",
}

local dongzhao = General:new(extension, "rfenghou_3d9j__dongzhao", "wei", 3)

Fk:loadTranslationTable{
  ["rfenghou_3d9j__dongzhao"] = "董昭",
  ["#rfenghou_3d9j__dongzhao"] = "定鼎移尊",
  ["designer:rfenghou_3d9j__dongzhao"] = "GENTOVA",
  ["~rfenghou_3d9j__dongzhao"] = "昭，一心向魏，绝无二心……",
}

local xianshi = fk.CreateTriggerSkill{
  name = "rfenghou__xianshi",
  anim_type = "control",
  events = {fk.TurnStart},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and not target.dead then
      return #player:getTableMark("rfenghou__xianshi_choice-round") < 2
    end
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, data, "#rfenghou__xianshi-invoke:"..target.id)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local n = 3
    if player:getMark("rfenghou__xianshi_noboubling-round") == 0 then
      n = 2 * n
    end
    local cards = room:getNCards(n)
    local all_choices = {"rfenghou__xianshi_show", "rfenghou__xianshi_discard"}
    local used = player:getTableMark("rfenghou__xianshi_choice-round")
    local choices = table.filter(all_choices, function (name) return not table.contains(used, name) end)
    local _, choice = U.askforChooseCardsAndChoice(player, cards, choices, self.name, "", {}, 0, 0)
    room:addTableMark(player, "rfenghou__xianshi_choice-round", choice)
    if choice == "rfenghou__xianshi_show" then
      local give_cards = room:askForPoxi(player, "rfenghou__xianshi", {
        { "Top", cards },
      }, nil, false)
      player:showCards(give_cards)
      room:obtainCard(target, give_cards, true, fk.ReasonJustMove, target.id, self.name)
      player.tag["rfenghou__xianshi_give"] = true
    else
      cards = room:askForCardsChosen(player, player, 1, #cards, { card_data = { { "弃置", cards } } },
      self.name, "#rfenghou__xianshi-discard")
      room:moveCardTo(cards, Card.DiscardPile, nil, fk.ReasonPutIntoDiscardPile, self.name)
    end
  end,

  refresh_events = {fk.RoundStart},
  can_refresh = function (self, event, target, player, data)
    return player.tag["rfenghou__xianshi_give"]
  end,
  on_refresh = function (self, event, target, player, data)
    player.tag["rfenghou__xianshi_give"] = nil
    player.room:setPlayerMark(player, "rfenghou__xianshi_noboubling-round", 1)
  end,
}
dongzhao:addSkill(xianshi)

Fk:addPoxiMethod{
  name = "rfenghou__xianshi",
  card_filter = function(to_select, selected, data, extra_data)
    if #selected == 0 then return true end
    return Fk:getCardById(to_select).color == Fk:getCardById(selected[1]).color
  end,
  feasible = function(selected, data, extra_data)
    return #selected > 0
  end,
  default_choice = function (data, extra_data)
    if data == nil then return {} end
    return {data[1][2][1]}
  end,
}

Fk:loadTranslationTable{
  ["rfenghou__xianshi"] = "先识",
  [":rfenghou__xianshi"] = "一名角色的回合开始时，你可以观看牌堆顶的三张牌（若你上轮发动“先识”没有角色获得牌，则翻倍），然后执行以下本轮未执行过的一项：展示其中任意数量相同颜色的牌，其获得之；将其中任意数量的牌置入弃牌堆。",
  ["#rfenghou__xianshi-invoke"] = "先识：“%src”的回合，你可以观看牌堆顶牌并选一项",
  ["rfenghou__xianshi_show"] = "展示同色牌",
  ["rfenghou__xianshi_discard"] = "置入弃牌堆",
  ["#rfenghou__xianshi-discard"] = "选择牌置入弃牌堆",

  ["$rfenghou__xianshi1"] = "行略于先，未雨绸缪。",
  ["$rfenghou__xianshi2"] = "先见梧叶，而后知秋。",
}

local zaowang = fk.CreateActiveSkill{
  name = "rfenghou__zaowang",
  anim_type = "control",
  card_num = 0,
  target_num = 1,
  frequency = Skill.Limited,
  prompt = "#rfenghou__zaowang",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    return #selected == 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:addPlayerMark(target, "@@zaowang", 1)
    if target.role == "rebel" then
      local tag = room.tag["rfenghou__zaowang_rebel"] or {}
      table.insertIfNeed(tag, target.id)
      room.tag["rfenghou__zaowang_rebel"] = tag
    end
    room:changeMaxHp(target, 1)
    if target:isWounded() and not target.dead then
      room:recover{
        who = target,
        num = 1,
        recoverBy = player,
        skillName = self.name,
      }
    end
    if not target.dead then
      target:drawCards(3, self.name)
    end
    room:setPlayerProperty(target, "role_shown", true)
    if target.role == "loyalist" then
      local lord = table.find(room.alive_players, function (p) return p.role == "lord" end)
      if lord then
        room:setPlayerProperty(lord, "role", "loyalist")
        room:setPlayerProperty(target, "role", "lord")
      end
    end
  end,
}
local zaowang_trigger = fk.CreateTriggerSkill{
  name = "#rfenghou__zaowang_trigger",

  refresh_events = {fk.GameOverJudge},
  can_refresh = function(self, event, target, player, data)
    local tag = player.room.tag["rfenghou__zaowang_rebel"] or Util.DummyTable
    return target == player and table.contains(tag, player.id)
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:gameOver("lord+loyalist")
  end,
}
zaowang:addRelatedSkill(zaowang_trigger)
dongzhao:addSkill(zaowang)

Fk:loadTranslationTable{
  ["rfenghou__zaowang"] = "造王",
  [":rfenghou__zaowang"] = "限定技，出牌阶段，你可以令一名其他角色加1点体力上限、回复1点体力并摸三张牌，然后亮出其身份牌。若其为：忠臣，其与主公交换身份牌；反贼，当其死亡时，主公方获胜。",
  ["@@rfenghou__zaowang"] = "造王",
  ["#rfenghou__zaowang"] = "造王：令一名角色加1点体力上限、回复1点体力并摸三张牌！",
  ["$rfenghou__zaowang1"] = "大魏当兴，吾主可王。",
  ["$rfenghou__zaowang2"] = "身加九锡，当君不让。",
}




local zhaoang = General:new(extension, "rfenghou_3d10j__zhaoang", "wei", 4)

local fenji = fk.CreateTriggerSkill{
  name = "setam__za_fenji",
  anim_type = "special",
  events = {fk.EventPhaseStart},
  can_trigger = function (self, event, target, player, data)
    if player:hasSkill(self) and player == target then
      return table.contains({Player.Draw, Player.Discard}, player.phase)
      and #player:getTableMark("@$setam__za_fenji") > 0
    end
  end,
  on_cost = function (self, event, target, player, data)
    local prompt = Fk:translate("#setam__za_fenji-prompt")
    local tab = {
      [Player.Draw] = {"摸牌数", "造成伤害值"},
      [Player.Discard] = {"弃牌数", "目标数"},
    }
    prompt = string.format(prompt, tab[player.phase][1], tab[player.phase][2])

    local _, ret = player.room:askForUseActiveSkill(player, "rfenghou_3d10j__za_fenji_viewas", prompt, true)
    if ret then
      self.cost_data = {ret.interaction, ret.targets}
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    if player.phase == Player.Discard then
      player._phase_end = true
    end
    local name, targets = table.unpack(self.cost_data)
    player.room:removeTableMark(player, "@$setam__za_fenji", name)
    local card = Fk:cloneCard(name)
    card.skillName = self.name
    player.room:useCard{
      from = player.id,
      tos = table.map(targets, function (id) return {id} end),
      card = card,
    }
  end,
  on_acquire = function (self, player, is_start)
    local mark = U.getAllCardNames("t")
    if not is_start then
      player.room.logic:getEventsOfScope(GameEvent.UseCard, 999, function (e)
        local use = e.data[1] ---@type CardUseStruct
        if use.card.skillName == self.name then
          table.removeOne(mark, use.card.name)
        end
      end, Player.HistoryGame)
    end
    player.room:setPlayerMark(player, "@$setam__za_fenji", mark)
  end,
  on_lose = function (self, player, is_death)
    player.room:setPlayerMark(player, "@$setam__za_fenji", 0)
  end,
}

local fenji_draw = fk.CreateTriggerSkill{
  name = "#setam__za_fenji_draw",
  mute = true,
  events = {fk.DrawNCards},
  can_trigger = function (self, event, target, player, data)
    if player:hasSkill(fenji) and player == target then
      return player:usedSkillTimes(fenji.name, Player.HistoryPhase) ~= 0
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    local n = #player.room.logic:getActualDamageEvents(999, function (e)
      local damage =  e.data[1] ---@type DamageStruct
      return damage.card and damage.card.skillName == fenji.name
    end)
    data.n = n
  end
}
fenji:addRelatedSkill(fenji_draw)
Fk:loadTranslationTable{ ["#setam__za_fenji_draw"] = "奋计" }

local fenji_discard = fk.CreateTriggerSkill{
  name = "#setam__za_fenji_discard",
  mute = true,
  events = {fk.EventPhaseEnd},
  can_trigger = function (self, event, target, player, data)
    if player:hasSkill(fenji) and player == target then
      return player:usedSkillTimes(fenji.name, Player.HistoryPhase) ~= 0
      and player.phase == Player.Discard
    end
  end,
  on_trigger = function (self, event, target, player, data)
    local n = 0
    player.room.logic:getEventsOfScope(GameEvent.UseCard, 1, function (e)
      local use = e.data[1] ---@type CardUseStruct
      if use.card and use.card.skillName == fenji.name then
        n = #TargetGroup:getRealTargets(use.tos)
        return true
      end
    end, Player.HistoryPhase)

    local canDiscards = table.filter(
      player:getCardIds{ Player.Hand }, function(id)
        local card = Fk:getCardById(id)

        local status_skills = Fk:currentRoom().status_skills[MaxCardsSkill] or Util.DummyTable
        for _, skill in ipairs(status_skills) do
          if skill:excludeFrom(player, card) then
            return false
          end
        end
        return true
      end
    )
    if #canDiscards == 0 then return end
    n = math.min(n, #canDiscards)

    local toDiscard

    local dis_data = {
      num = n,
      min_num = n,
      include_equip = false,
      skillName = "phase_discard",
      pattern = ".",
    }
    local _, ret = player.room:askForUseActiveSkill(player, "discard_skill", "#setam__za_fenji-discard:::"..n, false, dis_data)

    if ret then
      toDiscard = ret.cards
    else
      toDiscard = table.random(canDiscards, n) ---@type integer[]
    end

    player.room:throwCard(toDiscard, "phase_discard", player, player)
  end
}
fenji:addRelatedSkill(fenji_discard)
Fk:loadTranslationTable{ ["#setam__za_fenji_discard"] = "奋计" }

local fenji_viewas = fk.CreateViewAsSkill{
  name = "rfenghou_3d10j__za_fenji_viewas",
  interaction = function (self, player)
    local all_choices = U.getAllCardNames("t")
    local choices = U.getViewAsCardNames(player, fenji.name, player:getTableMark("@$setam__za_fenji"))
    return U.CardNameBox { all_choices = all_choices, choices = choices }
  end,
  card_filter = Util.FalseFunc,
  view_as = function (self, cards, player)
    local name = self.interaction.data
    if not name or #cards ~= 0 then return end
    local card = Fk:cloneCard(name)
    card.skillName = self.name
    return card
  end,
}
Fk:addSkill(fenji_viewas)
Fk:loadTranslationTable{ ["rfenghou_3d10j__za_fenji_viewas"] = "奋计" }

zhaoang:addSkill(fenji)

Fk:loadTranslationTable{
  ["rfenghou_3d10j__zhaoang"] = "赵昂",
  ["#rfenghou_3d10j__zhaoang"] = "局倾九持",
  ["designer:rfenghou_3d10j__zhaoang"] = "君腾天下",
  ["~rfenghou_3d10j__zhaoang"] = "援军为何迟迟不至？",

  ["setam__za_fenji"] = "奋计",
  [":setam__za_fenji"] = "摸牌/弃牌阶段开始时，你可以视为使用一张未以此法使用过的普通锦囊牌，然后将此阶段摸牌/弃牌数改为该牌造成伤害值/目标数。",

  ["#setam__za_fenji-prompt"] = "奋计：可以视为使用一张普通锦囊牌，将此阶段%s改为该牌%s",
  ["@$setam__za_fenji"] = "奋计",
  ["#setam__za_fenji-discard"] = "奋计：请弃置 %arg 张牌",

  ["$setam__za_fenji1"] = "敌众我寡，怎可少谋？",
  ["$setam__za_fenji2"] = "临城据守，当出奇计。",
}

local zhouchu = General:new(extension, "rfenghou_3d12j__zhouchu", "wu", 5)

local xiaheng = fk.CreateTriggerSkill{
  name = "rfenghou__xiaheng",
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  dynamic_desc = function(self, player)
    local tail = ""
    if player:getMark(self.name) ~= 1 then
      tail = Fk:translate("rfenghou__xiaheng_to_delete")
    end
    return "rfenghou__xiaheng_inner:" .. tail
  end,
  events = {fk.EventPhaseStart},
  can_trigger = function (self, event, target, player, data)
    if player:hasSkill(self) and player == target then
      return player.phase == Player.Play
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local playerA, playerB ---@type ServerPlayer, ServerPlayer
    local tos = table.filter(room:getAlivePlayers(false), function (p)
      return not p:isNude()
    end)
    if #tos > 0 then
      tos = table.map(tos, Util.IdMapper)
      playerA = room:getPlayerById(room:askForChoosePlayers(player, tos, 1, 1, "#rfenghou__xiaheng-choose", self.name, false)[1])
      room:addTableMarkIfNeed(player, "rfenghou__xiaheng_chosen", playerA.id)
      local num = math.min(2, #playerA:getCardIds("he"))
      local cards = room:askForCardsChosen(player, playerA, num, num, "he", self.name, "#rfenghou__xiaheng-discard:"..playerA.id)
      room:throwCard(cards, self.name, playerA, player)
    end

    tos = table.map(room:getAlivePlayers(false), Util.IdMapper)
    if #tos > 0 then
      playerB = room:getPlayerById(room:askForChoosePlayers(player, tos, 1, 1, "#rfenghou__xiaheng-damage", self.name, false)[1])
      room:addTableMarkIfNeed(player, "rfenghou__xiaheng_chosen", playerB.id)
      room:damage{
        damage = 1,
        to = playerB,
        from = player,
        skillName = self.name,
      }
    end

    if playerA and playerB and player:getMark(self.name) == 0 then
      if not table.contains({playerA, playerB}, player) then
        room:changeMaxHp(player, -1)
      end
      if playerA == playerB then
        room:loseHp(player, 1, self.name)
      end
    end

    if player:getMark(self.name) == 0 and #player:getTableMark("rfenghou__xiaheng_chosen") == 3 then
      room:notifySkillInvoked(player, self.name, "big")
      room:setPlayerMark(player, self.name, 1)
    end
  end,
}
zhouchu:addSkill(xiaheng)

Fk:loadTranslationTable{
  ["rfenghou_3d12j__zhouchu"] = "周处",
  ["#rfenghou_3d12j__zhouchu"] = "云蛟何惧",
  ["designer:rfenghou_3d12j__zhouchu"] = "志文",

  ["rfenghou__xiaheng"] = "侠横",
  [":rfenghou__xiaheng"] = "锁定技，出牌阶段开始时，你弃置一名角色两张牌（不足则全弃），再对一名角色造成1点伤害。"
  .."【若两名角色，均不为你，你减1点体力上限；为同一名角色，你失去1点体力；】"
  .."然后若以此法选择包括你在内三名不同的角色，你删除【】中的内容。",
  [":rfenghou__xiaheng_inner"] = "锁定技，出牌阶段开始时，你弃置一名角色两张牌（不足则全弃），再对一名角色造成1点伤害。{1}",
  ["rfenghou__xiaheng_to_delete"] = "【若两名角色，均不为你，你减1点体力上限；为同一名角色，你失去1点体力；】然后若以此法选择包括你在内三名不同的角色，你删除【】中的内容。",

  ["#rfenghou__xiaheng-choose"] = "侠横：弃置一名角色两张牌（不足则全弃）",
  ["#rfenghou__xiaheng-discard"] = "侠横：弃置 %src 两张牌（不足则全弃）",
  ["#rfenghou__xiaheng-damage"] = "侠横：对一名角色造成1点伤害",
}

local xiangchong = General:new(extension, "rfenghou_3d13j__xiangchong", "shu", 4)

local rfenghou_3d13j__wanzhen = fk.CreateViewAsSkill{
  name = "rfenghou_3d13j__wanzhen",
  anim_type = "special",
  prompt = function ()
    return Self.chained and "#rfenghou_3d13j__wanzhen-viewas2:::"..Self:getMark("@rfenghou_3d13j__wanzhen") or "#rfenghou_3d13j__wanzhen-viewas1"
  end,
  pattern = ".|.|.|.|.|basic",
  interaction = function()
    local all_names = {}
    all_names = U.getAllCardNames("b")
    local names = U.getViewAsCardNames(Self, "rfenghou_3d13j__wanzhen", all_names)
    if #names > 0 then
      return UI.ComboBox { choices = names, all_choices = all_names }
    end
  end,
  card_filter = Util.FalseFunc,
  view_as = function(self, cards)
    if not self.interaction.data then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = self.name
    return card
  end,
  before_use = function(self, player)
    local room = player.room
    local num = player:getMark("@rfenghou_3d13j__wanzhen")
    local trueinvoke = false
      if not player.chained then
        trueinvoke = true
        player:setChainState(true)
        if not player.dead then
          room:setPlayerMark(player, "@rfenghou_3d13j__wanzhen", 3)
        end
      elseif player.chained then
        player:setChainState(false)
        if not player.dead then
          if num > 0 then
            room:askForDiscard(player, num, num, true, self.name, false)
            room:setPlayerMark(player, "@rfenghou_3d13j__wanzhen", 0)
          else
            room:setPlayerMark(player, "@rfenghou_3d13j__wanzhen", 0)
          end
        end
      end
    if not trueinvoke then return "" end
    end,
  enabled_at_play = function(self, player)
    local can = table.filter(player.player_cards[Player.Hand], function(id) return not player:prohibitDiscard(Fk:getCardById(id)) end)
    return not player.chained or (player.chained and #can >= player:getMark("@rfenghou_3d13j__wanzhen"))
  end,
  enabled_at_response = function(self, player, res)
    local can = table.filter(player.player_cards[Player.Hand], function(id) return not player:prohibitDiscard(Fk:getCardById(id)) end)
    return not player.chained or (player.chained and #can >= player:getMark("@rfenghou_3d13j__wanzhen"))
  end,
}
local rfenghou_3d13j__wanzhen_trigger = fk.CreateTriggerSkill{
  name = "#rfenghou_3d13j__wanzhen_trigger",
  mute = true,

  refresh_events = {fk.AfterCardUseDeclared, fk.ChainStateChanged},
  can_refresh = function (self, event, target, player, data)
    if event == fk.AfterCardUseDeclared then
      return target == player and player:getMark("@rfenghou_3d13j__wanzhen") > 0
    elseif event == fk.ChainStateChanged then
      return target == player and not player.chained
    end
  end,
  on_refresh = function (self, event, target, player, data)
    if event == fk.AfterCardUseDeclared then
      player.room:removePlayerMark(player, "@rfenghou_3d13j__wanzhen", 1)
    elseif event == fk.ChainStateChanged then
      player.room:setPlayerMark(player, "@rfenghou_3d13j__wanzhen", 0)
    end
  end,
}

rfenghou_3d13j__wanzhen:addRelatedSkill(rfenghou_3d13j__wanzhen_trigger)
xiangchong:addSkill(rfenghou_3d13j__wanzhen)

Fk:loadTranslationTable{
  ["rfenghou_3d13j__xiangchong"] = "向宠",
  ["#rfenghou_3d13j__xiangchong"] = "岂止岳能",
  ["designer:rfenghou_3d13j__xiangchong"] = "拉普拉斯",
  ["illustrator:rfenghou_3d13j__xiangchong"] = "鬼画府",

  ["rfenghou_3d13j__wanzhen"] = "完阵",
  [":rfenghou_3d13j__wanzhen"] = "当你需要使用或打出基本牌时，你可以横置，视为使用或打出之，或重置并弃置3-X张牌（X为你因此横置期间使用的牌数且至多为3）。",

  ["@rfenghou_3d13j__wanzhen"] = "完阵弃牌",
  ["#rfenghou_3d13j__wanzhen_trigger"] = "完阵",
  ["#rfenghou_3d13j__wanzhen-viewas1"] = "完阵：你可横置武将牌，视为使用或打出基本牌（能以此法转化）",
  ["#rfenghou_3d13j__wanzhen-viewas2"] = "完阵：你可重置武将牌，然后弃置 %arg 张牌（以此法转化牌作废）",

  ["~rfenghou_3d13j__xiangchong"] = "",
}

local xumu = General:new(extension, "rfenghou_3d13j__xumu", "shu", 3, 3, General.Female)

local rfenghou_3d13j__yanchi = fk.CreateTriggerSkill{
  name = "rfenghou_3d13j__yanchi",
  anim_type = "offensive",
  events = {fk.TurnStart},
  can_trigger = function(self, event, target, player, data)
    local cards = table.filter(player:getCardIds("h"), function (id)
      return Fk:getCardById(id).color == Card.Black or Fk:getCardById(id).type == Card.TypeBasic
    end)
    return player:hasSkill(self) and target.hp > player.hp and player:canPindian(target) and #cards > 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:doIndicate(player.id, {target.id})
    local pindian = player:pindian({target}, self.name)
    if target.dead or player:isProhibited(target, Fk:cloneCard("slash")) then return end
    if pindian.results[target.id].winner == player or
      (pindian.fromCard.color == Card.Black and pindian.fromCard.type == Card.TypeBasic) then
      if room:askForSkillInvoke(player, self.name, data, "#rfenghou_3d13j__yanchi-slash::"..target.id) then
        local card = Fk:cloneCard("slash")
        card.skillName = self.name
        card:addSubcard(pindian.fromCard)
        local use = {
          from = player.id,
          tos = {{target.id}},
          card = card,
          extraUse = true,
        }
        room:useCard(use)
      end
    end
  end
}
local rfenghou_3d13j__yanchi_trigger = fk.CreateTriggerSkill{
  name = "#rfenghou_3d13j__yanchi_trigger",
  mute = true,
  events = {fk.StartPindian},
  can_trigger = function(self, event, target, player, data)
    if player == data.from and data.reason == "rfenghou_3d13j__yanchi" then
      return true
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards = table.filter(player:getCardIds("h"), function (id)
      return Fk:getCardById(id).color == Card.Black or Fk:getCardById(id).type == Card.TypeBasic
    end)
    if #cards > 0 then
      local card = room:askForCard(player, 1, 1, false, "rfenghou_3d13j__yanchi", false, tostring(Exppattern{ id = cards }),
        "#rfenghou_3d13j__yanchi-pindian")
      data.fromCard = data.fromCard or {}
      data.fromCard = Fk:getCardById(card[1])
    end
  end,
}

local rfenghou_3d13j__zhaozhong = fk.CreateTriggerSkill{
  name = "rfenghou_3d13j__zhaozhong",
  attached_skill_name = "rfenghou_3d13j__zhaozhong&",

  refresh_events = {fk.PindianResultConfirmed},
  can_refresh = function(self, event, target, player, data)
    return data.winner == player
  end,
  on_refresh = function(self, event, target, player, data)
    player.room:setPlayerMark(player, "@@rfenghou_3d13j__zhaozhong", 0)
  end,

  on_lose = function (self, player, is_death)
    player.room:setPlayerMark(player, "@@rfenghou_3d13j__zhaozhong", 0)
  end,
}

local rfenghou_3d13j__zhaozhong_active = fk.CreateActiveSkill{
  name = "rfenghou_3d13j__zhaozhong&",
  anim_type = "support",
  prompt = "#rfenghou_3d13j__zhaozhong-active",
  card_num = 1,
  target_num = 1,
  can_use = function(self, player)
    return not player:isKongcheng()
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0 and (Fk:getCardById(to_select).trueName == "jink" or Fk:getCardById(to_select).trueName == "peach")
  end,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and to_select ~= Self.id and Fk:currentRoom():getPlayerById(to_select):hasSkill("rfenghou_3d13j__zhaozhong")
    and Fk:currentRoom():getPlayerById(to_select):getMark("rfenghou_3d13j__zhaozhong-phase") == 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:setPlayerMark(target, "rfenghou_3d13j__zhaozhong-phase", 1)
    player:broadcastSkillInvoke("rfenghou_3d13j__zhaozhong")
    room:obtainCard(target, effect.cards[1], false, fk.ReasonGive)
    if player.dead or target.dead or not table.find(room:getOtherPlayers(target), function(p) return
      not target:isProhibited(p, Fk:cloneCard("ex_nihilo")) end) then return end
      local tos = room:askForChoosePlayers(player, table.map(table.filter(room:getAllPlayers(), function(p) return
        not target:isProhibited(p, Fk:cloneCard("ex_nihilo")) end), Util.IdMapper),  1, 1, "#rfenghou_3d13j__zhaozhong_ex_nihilo::"..effect.tos[1], self.name, false)
      if #tos > 0 then
        local tar = room:getPlayerById(tos[1])
        if room:askForSkillInvoke(target, self.name, nil, "#rfenghou_3d13j__zhaozhong_nil::"..tos[1]) then
          room:useVirtualCard("ex_nihilo", nil, target, tar, self.name, true)
        else
          room:setPlayerMark(target, "@@rfenghou_3d13j__zhaozhong", 1)
        end
      end
  end,
}

local rfenghou_3d13j__zhaozhong_invalidity = fk.CreateInvaliditySkill {
  name = "#rfenghou_3d13j__zhaozhong_invalidity",
  invalidity_func = function(self, from, skill)
    return skill == rfenghou_3d13j__zhaozhong and from:getMark("@@rfenghou_3d13j__zhaozhong") > 0
  end
}

rfenghou_3d13j__yanchi:addRelatedSkill(rfenghou_3d13j__yanchi_trigger)
xumu:addSkill(rfenghou_3d13j__yanchi)
Fk:addSkill(rfenghou_3d13j__zhaozhong_active)
rfenghou_3d13j__zhaozhong:addRelatedSkill(rfenghou_3d13j__zhaozhong_invalidity)
xumu:addSkill(rfenghou_3d13j__zhaozhong)

Fk:loadTranslationTable{
  ["rfenghou_3d13j__xumu"] = "徐母",
  ["#rfenghou_3d13j__xumu"] = "暮榆犹树",
  ["designer:rfenghou_3d13j__xumu"] = "拼音",
  ["illustrator:rfenghou_3d13j__xumu"] = "大佬荣",

  ["rfenghou_3d13j__yanchi"] = "砚斥",
  [":rfenghou_3d13j__yanchi"] = "体力值大于你的角色的回合开始时，你可以用一张黑色牌或基本牌与其拼点，若之为黑色基本牌或你赢，你可以将你的拼点牌当【杀】对其使用。",
  ["rfenghou_3d13j__zhaozhong"] = "召忠",
  [":rfenghou_3d13j__zhaozhong"] = "其他角色的出牌阶段限一次，其可以将一张【闪】或【桃】交给你并令你视为对其选择的一名角色使用【无中生有】；你可以拒绝使用，然后令“召忠”无效直至你拼点赢。",

  ["#rfenghou_3d13j__yanchi_trigger"] = "砚斥",
  ["#rfenghou_3d13j__yanchi-slash"] = "砚斥：是否将你的拼点牌当【杀】对 %dest 使用？",
  ["#rfenghou_3d13j__yanchi-pindian"] = "砚斥：请选择一张黑色牌或基本牌拼点！若为黑色基本牌则必定触发后续。",
  ["rfenghou_3d13j__zhaozhong&"] = "召忠",
  [":rfenghou_3d13j__zhaozhong&"] = "出牌阶段限一次，你可以将一张【闪】或【桃】交给一名有召忠的角色，令其对你选择的目标使用【无中生有】。",
  ["#rfenghou_3d13j__zhaozhong-active"] = "召忠：将一张【闪】或【桃】交给一名有召忠的角色，令其对你选择的目标使用【无中生有】。",
  ["@@rfenghou_3d13j__zhaozhong"] = "召忠 失效",
  ["#rfenghou_3d13j__zhaozhong_ex_nihilo"] = "召忠：请选择一名 %dest 使用无中生有的目标角色",
  ["#rfenghou_3d13j__zhaozhong_nil"] = "召忠：是否 %dest 使用无中生有？点确认使用，点取消技能失效直至你拼点赢！",

  ["~rfenghou_3d13j__xumu"] = "",
}

local weizhao = General:new(extension, "rfenghou_3d13j__weizhao", "wu", 3)

local rfenghou_3d13j__jizhu = fk.CreateTriggerSkill{
  name = "rfenghou_3d13j__jizhu",
  anim_type = "support",
  events = {fk.CardUseFinished, fk.CardRespondFinished},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local ids = U.turnOverCardsFromDrawPile(player, 1, self.name)
    local cardlist = data.card:isVirtual() and data.card.subcards or {data.card.id}
    if Fk:translate(Fk:getCardById(ids[1]).trueName, "zh_CN"):len() == Fk:translate(data.card.trueName, "zh_CN"):len()
    and #cardlist > 0 and table.every(cardlist, function (id) return room:getCardArea(id) == Card.Processing end) then
      local to = room:askForChoosePlayers(player, table.map(table.filter(room.alive_players, function(p)
        return p ~= room.current end), Util.IdMapper), 1, 1, "#rfenghou_3d13j__jizhu-choose", self.name, false)
      if #to > 0 then
        local cards = room:getSubcardsByRule(data.card, { Card.Processing })
        table.insertIfNeed(cards, ids[1])
        room:moveCardTo(cards, Card.PlayerHand, room:getPlayerById(to[1]), fk.ReasonGive, self.name, nil, true, player.id)
      end
    end
    room:cleanProcessingArea(ids, self.name)
  end,
}

local rfenghou_3d13j__chuanjiu = fk.CreateFilterSkill{
  name = "rfenghou_3d13j__chuanjiu",
  card_filter = function(self, to_select, player)
    return player:hasSkill(self) and not player:isWounded() and (to_select.name == "peach" or to_select.name == "analeptic") and
    table.contains(player.player_cards[Player.Hand], to_select.id)
  end,
  view_as = function(self, to_select)
    return Fk:cloneCard("ex_nihilo", to_select.suit, to_select.number)
  end,
}
local rfenghou_3d13j__chuanjiu_trigger = fk.CreateTriggerSkill{
  name = "#rfenghou_3d13j__chuanjiu_trigger",
  refresh_events = {fk.HpChanged, fk.MaxHpChanged},
  can_refresh = function(self, event, target, player, data)
    return player == target and player:hasSkill(rfenghou_3d13j__chuanjiu, true)
  end,
  on_refresh = function(self, event, target, player, data)
    player:filterHandcards()
  end,
}

rfenghou_3d13j__chuanjiu:addRelatedSkill(rfenghou_3d13j__chuanjiu_trigger)
weizhao:addSkill(rfenghou_3d13j__jizhu)
weizhao:addSkill(rfenghou_3d13j__chuanjiu)

Fk:loadTranslationTable{
  ["rfenghou_3d13j__weizhao"] = "韦昭",
  ["#rfenghou_3d13j__weizhao"] = "酌荼注史",
  ["designer:rfenghou_3d13j__weizhao"] = "Ace",
  ["illustrator:rfenghou_3d13j__weizhao"] = "恶童",

  ["rfenghou_3d13j__jizhu"] = "籍注",
  [":rfenghou_3d13j__jizhu"] = "当你使用或打出牌时，你可以亮出牌堆顶的牌，若二者牌名字数相等，你将这两张牌交给一名非当前回合角色。",
  ["rfenghou_3d13j__chuanjiu"] = "荈酒",
  [":rfenghou_3d13j__chuanjiu"] = "锁定技，若你未受伤，你的【桃】与【酒】均视为【无中生有】。",

  ["#rfenghou_3d13j__jizhu-choose"] = "籍注：请将亮出牌交给一名非当前回合角色！",

  ["~rfenghou_3d13j__weizhao"] = "",
}

local lie = General:new(extension, "rfenghou_3d14j__lie", "wu", 3, 3, General.Female)

local rfenghou_3d14j__yeshen = fk.CreateTriggerSkill{
  name = "rfenghou_3d14j__yeshen",
  anim_type = "support",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target.phase == Player.Finish
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local x = player:getMark("@rfenghou_3d14j__yeshen")
    local ids = U.turnOverCardsFromDrawPile(player, x, self.name)
    local blacks = table.filter(ids, function (id) return Fk:getCardById(id).color == Card.Black end)
    if #blacks > 0 then
      local c = room:askForCard(target, 1, 1, false, self.name, false, ".|.|.|^(hand,equip,judge)", "#rfenghou_3d14j__yeshen-choose", blacks)
      if #c == 1 then
        local y = Fk:translate(Fk:getCardById(c[1]).trueName, "zh_CN"):len()
        local to = player.room:askForChoosePlayers(target, table.map(table.filter(room:getAllPlayers(), function(p)
          return target:canUseTo(Fk:cloneCard("iron_chain"), p) end), Util.IdMapper), y, y, "#rfenghou_3d14j__yeshen-use:::"..y, self.name, true)
          if #to == y and y > 0 then
            local card = Fk:cloneCard("iron_chain")
            card.skillName = self.name
            card:addSubcard(Fk:getCardById(c[1]))
            local use = {
              from = target.id,
              tos = {to},
              card = card,
              extraUse = true,
            }
            room:useCard(use)
          else
            room:recastCard(c, target, self.name)
          end
          local blacksleft = table.filter(ids, function (id) return room:getCardArea(id) == Card.Processing end)
          if #blacksleft > 0 and not target.dead then
            blacksleft = room:askForGuanxing(target, blacksleft, { #blacksleft, #blacksleft }, { 0, 0 }, self.name, true).top
            blacksleft = table.reverse(blacksleft)
          end
          room:moveCards({
            ids = blacksleft,
            from = target.id,
            toArea = Card.DrawPile,
            moveReason = fk.ReasonJustMove,
            skillName = self.name,
            proposer = target.id,
          })
        room:removePlayerMark(player, "@rfenghou_3d14j__yeshen", 1)
      end
      if not player.dead and player:getMark("@rfenghou_3d14j__yeshen") == 0 then
        room:setPlayerMark(player, "@rfenghou_3d14j__yeshen", 3)
        room:damage {
          from = player, to = player,
          damage = 1, damageType = fk.FireDamage, skillName = self.name
        }
      end
    else
      room:setPlayerMark(player, "@rfenghou_3d14j__yeshen", 3)
      room:damage {
        from = player, to = player,
        damage = 1, damageType = fk.FireDamage, skillName = self.name
      }
    end
    room:cleanProcessingArea(ids, self.name)
  end,

  on_acquire = function (self, player, is_start)
    player.room:setPlayerMark(player, "@rfenghou_3d14j__yeshen", 3)
  end,
  on_lose = function (self, player, is_death)
    player.room:setPlayerMark(player, "@rfenghou_3d14j__yeshen", 0)
  end,
}

local rfenghou_3d14j__qiaoduan = fk.CreateTriggerSkill{
  name = "rfenghou_3d14j__qiaoduan",
  anim_type = "offensive",
  events = {fk.ChainStateChanged},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      if target.chained then
        local x = #table.filter(player.room:getAllPlayers(), function(p) return p.chained end)
        return player:getMark("rfenghou_3d14j__qiaoduan1-turn") == 0 and #player:getCardIds("he") >= x
      elseif not target.chained then
        return player:getMark("rfenghou_3d14j__qiaoduan2-turn") == 0
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local x = #table.filter(room:getAllPlayers(), function(p) return p.chained end)
      if target.chained then
        room:setPlayerMark(player, "rfenghou_3d14j__qiaoduan1-turn", 1)
        local to = player.room:askForChoosePlayers(player, table.map(table.filter(room:getAllPlayers(), function(p)
        return p:isWounded() end), Util.IdMapper), 1, 1, "#rfenghou_3d14j__qiaoduan-choose1:::"..x, self.name, true)
        if #to > 0 then
          self.cost_data = to[1]
          return true
        end
      elseif not target.chained then
       room:setPlayerMark(player, "rfenghou_3d14j__qiaoduan2-turn", 1)
      local to = player.room:askForChoosePlayers(player, table.map(room:getAllPlayers(), Util.IdMapper),
      1, x, "#rfenghou_3d14j__qiaoduan-choose2:::"..x, self.name, true)
        if #to > 0 then
          self.cost_data = to
          return true
        end
      end
    end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if target.chained then
      local x = #table.filter(room:getAllPlayers(), function(p) return p.chained end)
      local cards = room:askForCard(player, x, x, true, self.name, false, ".", "#rfenghou_3d14j__qiaoduan-card:::"..x)
      if #cards > 0 then
        if #cards > 1 then
          cards = room:askForGuanxing(player, cards, { 0, 0 }, { #cards, #cards }, self.name, true).bottom
          cards = table.reverse(cards)
        end
        room:moveCards({
          ids = cards,
          from = player.id,
          toArea = Card.DrawPile,
          moveReason = fk.ReasonJustMove,
          skillName = self.name,
          proposer = player.id,
          drawPilePosition = -1,
        })
      end
      local to = room:getPlayerById(self.cost_data)
      if not to.dead and to:isWounded() then
        room:recover({
          who = to,
          num = 1,
          recoverBy = player,
          skillName = self.name
        })
      end
    elseif not target.chained then
      room:sortPlayersByAction(self.cost_data)
      for _, pid in ipairs(self.cost_data) do
        local to = room:getPlayerById(pid)
        if not to.dead then
          room:drawCards(to, 1, self.name)
        end
      end
    end
  end,
}
lie:addSkill(rfenghou_3d14j__yeshen)
lie:addSkill(rfenghou_3d14j__qiaoduan)

Fk:loadTranslationTable{
  ["rfenghou_3d14j__lie"] = "李娥",
  ["#rfenghou_3d14j__lie"] = "烬焚赤心",
  ["designer:rfenghou_3d14j__lie"] = "yyuan",
  ["illustrator:rfenghou_3d14j__lie"] = "未知",

  ["rfenghou_3d14j__yeshen"] = "冶身",
  [":rfenghou_3d14j__yeshen"] = "一名角色的结束阶段，你可以亮出牌堆底三张牌，若其中有黑色牌，其将其中一张当额定目标数为牌名字数的【铁索连环】使用或重铸，令“冶身”亮出牌数-1，"..
  "然后将其余牌置于牌堆顶，若没有黑色牌或亮出牌数因此减至0，你复原“冶身”并对自己造成1点火焰伤害。",
  ["rfenghou_3d14j__qiaoduan"] = "巧锻",
  [":rfenghou_3d14j__qiaoduan"] = "每回合首次有角色的武将牌被：横置后，你可以将X张牌置于牌堆底，令一名角色回复1点体力；重置后，你可以令至多X名角色各摸一张牌(X为处于连环状态的角色数)。",

  ["@rfenghou_3d14j__yeshen"] = "冶身",
  ["#rfenghou_3d14j__yeshen-choose"] = "冶身：请选择一张用于转化【铁索连环】或重铸的牌！（若使用，额定目标数为牌名字数，否则重铸！）",
  ["#rfenghou_3d14j__yeshen-use"] = "冶身：请选择 %arg 名角色作为【铁索连环】的目标，否则重铸先前选择的牌！",
  ["#rfenghou_3d14j__qiaoduan-choose1"] = "巧锻：是否令一名角色回复1点体力（选择后，你须先将 %arg 张牌置于牌堆底）",
  ["#rfenghou_3d14j__qiaoduan-choose2"] = "巧锻：是否令至多 %arg 名角色各摸一张牌？",
  ["#rfenghou_3d14j__qiaoduan-card"] = "巧锻：请将 %arg 张牌置于牌堆底！",

  ["~rfenghou_3d14j__lie"] = "",
}

--[[

鲍信
群，德昭济北，4体力 des：突然消失 角标：3D14
先觉——
锁定技，你跳过除准备阶段外的所有额定阶段；准备阶段，你观看牌堆顶的五张牌并使用其中任意张，然后依次执行之后X个额外的阶段（X为这些牌中造成伤害的牌数）。

]]

local qinlang = General:new(extension, "rfenghou_3d15j__qinlang", "wei", 4)

local zhengyun = fk.CreateViewAsSkill{
  name = "setam__zhengyun",
  anim_type = "control",
  prompt = function ()
    return string.format(Fk:translate("#setam__zhengyun-prompt"), 1, Fk:translate("chasing_near"))
  end,
  pattern = "chasing_near",
  card_filter = function (self, to_select, selected, player)
    if #selected > 0 then return false end
    return Fk:getCardById(to_select).is_damage_card
  end,
  view_as = function (self, cards, player)
    if #cards == 0 then return end
    local card = Fk:cloneCard("chasing_near")
    card.skillName = self.name
    card:addSubcards(cards)
    return card
  end,
  enabled_at_play = Util.TrueFunc,
  enabled_at_response = function (self, player, response)
    return not response
  end
}

local zhengyun_viewas = fk.CreateViewAsSkill{ -- card_name, num, card_ids
  name = "rfenghou__zhengyun_viewas",
  card_filter = function (self, to_select, selected, player)
    if #selected > self.num then return false end
    return Fk:getCardById(to_select).is_damage_card
    and table.contains(self.card_ids, to_select)
  end,
  view_as = function (self, cards, player)
    if #cards ~= self.num then return end
    local card = Fk:cloneCard(self.card_name)
    card.skillName = zhengyun.name
    card:addSubcards(cards)
    return card
  end
}
Fk:addSkill(zhengyun_viewas)
Fk:loadTranslationTable{ ["rfenghou__zhengyun_viewas"] = "征云" }

local zhengyun_delay = fk.CreateTriggerSkill{
  name = "#setam__zhengyun_delay",
  mute = true,
  events = {fk.CardUseFinished},
  can_trigger = function (self, event, target, player, data)
    if player:hasSkill(zhengyun) and player == target then
      return data.card.skillName == zhengyun.name
      and not (data.extra_data and data.extra_data.rfenghou__zhengyun_index)
    end
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local cards = player:getTableMark(zhengyun.name) ---@type integer[]
    local card_names = {"chasing_near", "ex_nihilo", "reinforcement"}
    local num = table.indexOf(card_names, data.card.name)
    if #table.filter(cards, function(id) return Fk:getCardById(id).is_damage_card end) < num then return end

    if table.contains({"chasing_near", "ex_nihilo"}, data.card.name) then -- 2-
      local card_name = card_names[(num + 1)]
      local prompt = string.format(Fk:translate("#setam__zhengyun-prompt"), num, Fk:translate(card_name))
      local extra = { card_name = card_name, card_ids = cards, num = num }

      local _, ret = room:askForUseActiveSkill(player, zhengyun_viewas.name, prompt, true, extra)
      if ret then
        local card = Fk:cloneCard(card_name)
        card.skillName = zhengyun.name
        card:addSubcards(ret.cards)
        room:useCard{
          from = player.id,
          tos = table.map(ret.targets, function (id) return {id} end),
          card = card,
        }
      end

    else -- 3
      local extra_index = 1
      card_names = {}
      room.logic:getEventsOfScope(GameEvent.UseCard, 3, function (e)
        local use = e.data[1] ---@type CardUseStruct
        if use.from == player.id and use.card:isCommonTrick() then
          table.insertIfNeed(card_names, use.card.name)
          return true
        end
        return false
      end, Player.HistoryTurn)
      while extra_index <= 3 do
        local card_name = card_names[1]
        local prompt = string.format(Fk:translate("#setam__zhengyun-prompt"), 1, Fk:translate(card_name))
        local extra = { card_name = card_name, card_ids = cards, num = 1 }

        local _, ret = room:askForUseActiveSkill(player, zhengyun_viewas.name, prompt, true, extra)
        if ret then
          local card = Fk:cloneCard(card_name)
          card.skillName = zhengyun.name
          card:addSubcards(ret.cards)
          room:useCard{
            from = player.id,
            tos = table.map(ret.targets, function (id) return {id} end),
            card = card,
            extra_data = { rfenghou__zhengyun_index = extra_index },
          }
        else
          break
        end

        extra_index = extra_index + 1
      end
    end
  end
}
zhengyun:addRelatedSkill(zhengyun_delay)

local zhengyun_refresh = fk.CreateTriggerSkill{
  name = "#setam__zhengyun_refresh",
  mute = true,

  refresh_events = {fk.AfterCardsMove},
  can_refresh = function (self, event, target, player, data)
    return player:hasSkill(zhengyun)
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    local p = room.logic:getCurrentEvent():findParent(GameEvent.UseCard, true)
    if not (p and p.data[1].card.skillName == zhengyun.name) then return end
    local cardIds = {}
    for _, move in ipairs(data) do
      if move.to == player.id and move.toArea == Card.PlayerHand then
        for _, info in ipairs(move.moveInfo) do
          table.insertIfNeed(cardIds, info.cardId)
        end
      end
    end
    if #cardIds == 0 then return end
    room:setPlayerMark(player, zhengyun.name, cardIds)
  end
}
zhengyun:addRelatedSkill(zhengyun_refresh)
Fk:loadTranslationTable{ ["#setam__zhengyun_refresh"] = "征云" }

Fk:loadTranslationTable{ ["#setam__zhengyun_delay"] = "征云" }

qinlang:addSkill(zhengyun)

Fk:loadTranslationTable{
  ["rfenghou_3d15j__qinlang"] = "秦朗",
  ["#rfenghou_3d15j__qinlang"] = "纛立朔土",
  ["designer:rfenghou_3d15j__qinlang"] = "猪",

  ["setam__zhengyun"] = "征云",
  [":setam__zhengyun"] = "你可以将一张伤害类牌当【逐近弃远】使用；"
  .."然后可以将以上牌获得的一张伤害类牌当【无中生有】使用；"
  .."然后可以将以上牌获得的两张伤害类牌当【增兵减灶】使用；"
  .."然后可以将以上牌获得的三张伤害类牌依次当你本回合使用的前三张普通锦囊牌使用。",

  ["#setam__zhengyun-prompt"] = "征云：可以将%s张伤害类牌当【%s】使用",
}

local xukun = General:new(extension, "rfenghou_3d15j__xukun", "wu", 4)

local ninglan = fk.CreateViewAsSkill{
  name = "setam__ninglan",
  anim_type = "defensive",
  pattern = "nullification",
  view_as = function (self, cards, player)
    local card = Fk:cloneCard("nullification")
    card.skillName = self.name
    return card
  end,
  before_use = function (self, player, use)
    local room = player.room
    local tos = table.map(room:getAlivePlayers(false), Util.IdMapper)
    if #room.logic:getEventsOfScope(GameEvent.UseCard, 1, function (e)
      return e.data[1].from == player.id
      and e.data[1].card.name == "nullification"
    end, Player.HistoryRound) == 1 then
      tos = { player.id }
    end
    local to = room:askForChoosePlayers(player, tos, 1, 1, "#setam__ninglan-damage", self.name, false)[1]
    room:damage{
      from = player,
      to = room:getPlayerById(to),
      damage = 1,
      damageType = fk.IceDamage,
      skillName = self.name,
    }
  end
}

local ninglan_disrespone = fk.CreateTriggerSkill{
  name = "#setam__ninglan_disrespone",
  mute = true,
  events = {fk.CardUsing},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(ninglan) and data.card.skillName == ninglan.name
  end,
  on_trigger = function (self, event, target, player, data)
    data.disresponsiveList = data.disresponsiveList or {}
    for _, p in ipairs(player.room:getAlivePlayers(false)) do
      table.insertIfNeed(data.disresponsiveList, p.id)
    end
  end
}
ninglan:addRelatedSkill(ninglan_disrespone)
Fk:loadTranslationTable{ ["#setam__ninglan_disrespone"] = "凝澜" }

local ninglan_discard = fk.CreateTriggerSkill{
  name = "#setam__ninglan_discard",
  mute = true,
  events = {fk.DamageCaused},
  can_trigger = function (self, event, target, player, data)
    return player == target and player:hasSkill(ninglan) and data.skillName == ninglan.name
  end,
  on_trigger = function (self, event, target, player, data)
    local room = player.room
    local cancelable = #room.logic:getActualDamageEvents(1, function (e)
      return e.data[1].to == player
    end, Player.HistoryRound) == 0
    if not cancelable then
      for i = 1, 2 do
        if player.dead or data.to.dead or data.to:isNude() then break end
        local card = room:askForCardChosen(player, data.to, "he", "#tuntian_iceDamage")
        room:throwCard({card}, "#tuntian_iceDamage", data.to, player)
      end
      return true
    end
  end
}
ninglan:addRelatedSkill(ninglan_discard)
Fk:loadTranslationTable{ ["#setam__ninglan_discard"] = "凝澜" }

xukun:addSkill(ninglan)

---@param logic GameLogic
---@param player ServerPlayer
---@return string? @ 牌名
local function getFinalUse(logic, player)
	local events = logic.event_recorder[GameEvent.UseCard]
  if not events or #events == 0 then return nil end
  for i = #events, 1, -1 do
    local e = events[i]
    if e.data[1].from == player.id then
      local card = e.data[1].card
      if card.type == Card.TypeBasic or card:isCommonTrick() then
        return card.name
      end
    end
  end
  return nil
end

local jituan_viewas = fk.CreateViewAsSkill{
  name = "rfenghou__jituan_viewas",
  card_filter = function (self, to_select, selected, player)
    return #selected == 0 and Fk:currentRoom():getCardArea(to_select) == Card.PlayerHand
  end,
  view_as = function (self, cards, player)
    if #cards ~= 1 then return end
    local card = Fk:cloneCard(self.card_name)
    card.skillName = "rfenghou__jituan"
    card:addSubcards(cards)
    return card
  end,
}
Fk:addSkill(jituan_viewas)
Fk:loadTranslationTable{ ["rfenghou__jituan_viewas"] = "击湍" }

local jituan = fk.CreateActiveSkill{
  name = "rfenghou__jituan",
  anim_type = "offensive",
  prompt = "#rfenghou__jituan-prompt",
  can_use = function (self, player, card, extra_data)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
    and not player:isKongcheng()
  end,
  card_num = 0,
  target_num = 1,
  card_filter = Util.FalseFunc,
  target_filter = function (self, to_select, selected, selected_cards, card, extra_data, player)
    if #selected > 0 then return false end
    return player:canPindian(Fk:currentRoom():getPlayerById(to_select))
  end,
  on_use = function (self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])

    local drawAndUse = function ()
      local name = getFinalUse(room.logic, player)
      if room:askForSkillInvoke(player, self.name, nil, "#rfenghou__jituan-draw") then
        player:drawCards(1, self.name)

        if not name then return end
        local card = Fk:cloneCard(name)
        card.skillName = self.name
        if player:isAlive() and not player:isKongcheng() and U.getDefaultTargets(player, card, true, false) then
          local _, ret = room:askForUseActiveSkill(player, jituan_viewas.name, "#rfenghou__jituan-viewas:::"..name, false, { card_name = name })
          if ret then
            card:addSubcards(ret.cards)
            room:useCard{
              from = player.id,
              tos = table.map(ret.targets, function (id) return {id} end),
              card = card,
            }
          end
        end
      end
    end

    local pindian = player:pindian({target}, self.name)
    if pindian.results[target.id].winner ~= player then
      drawAndUse()
    end

    if not player:isAlive() then return end
    local use = U.askForUseVirtualCard(room, player, "duel", nil, self.name, nil, false, true, true, true)
    if #room.logic:getEventsOfScope(GameEvent.Damage, 1, function (e)
      return e.data[1].to == player and e.data[1].card and e.data[1].card == use.card
    end, Player.HistoryPhase) == 1 then
      drawAndUse()
    end

    if not player:isAlive() or player:isKongcheng() then return end
    local tos = table.filter(room:getOtherPlayers(player, false), function (p)
      return player:canPindian(p)
    end)
    if #tos > 0 then
      local to = room:askForChoosePlayers(player, table.map(tos, Util.IdMapper), 1, 1, "#rfenghou__jituan-pindian", self.name, false)
      pindian = player:pindian(table.map(to, Util.Id2PlayerMapper), self.name)
      if pindian.results[to[1]].winner ~= player then
        drawAndUse()
      end
    end
  end
}

xukun:addSkill(jituan)

Fk:loadTranslationTable{
  ["rfenghou_3d15j__xukun"] = "徐琨",
  ["#rfenghou_3d15j__xukun"] = "苇舟逆浪",
  ["designer:rfenghou_3d15j__xukun"] = "zzcclll朱苦力",
  ["illustrator:rfenghou_3d15j__xukun"] = "Yi章",

  ["setam__ninglan"] = "凝澜",
  [":setam__ninglan"] = "你可以分配1点冰冻伤害，视为使用无法被响应的【无懈可击】； 若你本轮已受到过伤害，你须选择触发弃牌效果； 若你本轮已使用过【无懈可击】，你须将伤害分配给自己。",

  ["#setam__ninglan-damage"] = "凝澜：分配1点冰冻伤害",

  ["rfenghou__jituan"] = "击湍",
  [":rfenghou__jituan"] = "出牌阶段限一次，你可以依次：拼点、视为使用【决斗】、拼点，过程中每次没赢后，你可以摸一张牌，然后将一张手牌当【随机应变】使用。",

  ["#rfenghou__jituan-prompt"] = "击湍：你可以拼点、视为使用【决斗】、拼点<br/>过程中每次没赢后，你可以摸一张牌，将一张手牌当【随机应变】使用",
  ["#rfenghou__jituan-draw"] = "击湍：可以摸一张牌，将一张手牌当【随机应变】使用",
  ["#rfenghou__jituan-viewas"] = "击湍：将一张手牌当【%arg】使用",
  ["#rfenghou__jituan-pindian"] = "击湍：与一名角色拼点",
}

local zhaoe = General:new(extension, "rfenghou_3d15j__zhaoe", "qun", 4, 4, General.Female)

Fk:loadTranslationTable{
  ["rfenghou_3d15j__zhaoe"] = "赵娥",
  ["#rfenghou_3d15j__zhaoe"] = "罗袖赤血",
  ["designer:rfenghou_3d15j__zhaoe"] = "Nurture",
  ["cv:rfenghou_3d15j__zhaoe"] = "邪恶母蟑螂",
  ["illustrator:rfenghou_3d15j__zhaoe"] = "三国志大战",
  ["~rfenghou_3d15j__zhaoe"] = "父仇已报，请就刑戮。",
}

local cuixue = fk.CreateTriggerSkill{
  name = "rfenghou_3d15j__cuixue",
  frequency = Skill.Compulsory,
  events = {fk.TurnStart, fk.TurnEnd},
  can_trigger = function (self, event, target, player, data)
    if not player:hasSkill(self) or target ~= player then return false end
    if event == fk.TurnStart then
      return true
    else
      local cards = player:getCardIds("h")
      return #cards > 0 and table.every(cards, function(id) return Fk:getCardById(id).trueName == "slash" end)
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if event == fk.TurnStart then
      local choices = {"0", "1", "2"}
      local choice = room:askForChoice(player, choices, self.name, "#rfenghou_3d15j__cuixue-choice")
      room:setPlayerMark(player, "@rfenghou_3d15j__cuixue-turn", tostring(choice))
    else
      player:showCards(player:getCardIds("h"))
      local targets = table.map(room:getOtherPlayers(player, false), Util.IdMapper)
      if #targets == 0 then return false end
      local tos = room:askForChoosePlayers(player, targets, 1, 1, "#rfenghou_3d15j__cuixue-damage", self.name, false)
      if #tos > 0 then
        room:damage { from = player, to = room:getPlayerById(tos[1]), damage = 1, skillName = self.name }
      end
    end
  end,

  refresh_events = {fk.CardUsing},
  can_refresh = function (self, event, target, player, data)
    return data.card.trueName == "slash" and player:getMark("@rfenghou_3d15j__cuixue-turn") ~= 0
  end,
  on_refresh = function (self, event, target, player, data)
    data.additionalDamage = (data.additionalDamage or 0) + tonumber(player:getMark("@rfenghou_3d15j__cuixue-turn"))
  end,

  on_lose = function (self, player, is_death)
    player.room:setPlayerMark(player, "@rfenghou_3d15j__cuixue-turn", 0)
  end,
}

--- 获取某牌占用的手牌上限
---@param player Player
---@param card Card
---@retun integer
local function getMaxCardsOccupied (player, card)
  local maxcard_skills = Fk:currentRoom().status_skills[MaxCardsSkill] or Util.DummyTable
  if table.find(maxcard_skills, function(skill)
    return skill:excludeFrom(player, card)
  end) then return 0 end
  -- 在此处修改卡牌占用手牌上限
  if player:getMark("@rfenghou_3d15j__cuixue-turn") ~= 0 and card.trueName == "slash" then
    return tonumber(player:getMark("@rfenghou_3d15j__cuixue-turn")) or 1
  end
  return 1
end

-- 模拟弃牌阶段
---@param player ServerPlayer
local function discardPhase(player)
  local room = player.room
  local limit = player:getMaxCards()
  local occupied = 0
  for _, id in ipairs(player:getCardIds(Player.Hand)) do
    occupied = occupied + getMaxCardsOccupied(player, Fk:getCardById(id))
  end
  local discardNum = occupied - limit
  if discardNum <= 0 then return end
  local canDiscards = table.filter(player:getCardIds(Player.Hand), function(id)
    return getMaxCardsOccupied(player, Fk:getCardById(id)) > 0 and not player:prohibitDiscard(id)
  end)
  if #canDiscards == 0 then return end
  local default = {}
  local tempNum = discardNum
  for _, id in ipairs(canDiscards) do
    table.insert(default, id)
    tempNum = tempNum - getMaxCardsOccupied(player, Fk:getCardById(id))
    if tempNum <= 0 then break end
  end
  if #default == 0 then return end
  if #default < #canDiscards then
    local _ , dat = room:askForUseActiveSkill(player, "rfenghou_3d15j__discard_skill", "#rfenghou_3d15j__discard_skill:::"..discardNum, false,
    {skillName = "phase_discard", discardNum = discardNum})
    if dat then
      default = dat.cards
    end
  end
  room:throwCard(default, "phase_discard", player, player)
end

local maxcard_occupied_trigger = fk.CreateTriggerSkill{
  name = "#maxcard_occupied_trigger",
  --global = true,
  priority = 0.001,
  events = {fk.EventPhaseStart},
  can_trigger = function (self, event, target, player, data)
    if target == player and player.phase == Player.Discard and not player:isKongcheng() then
      return player:getMark("@rfenghou_3d15j__cuixue-turn") ~= 0
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    if player._phase_end then return end
    discardPhase(player)
    return true
  end,
}
cuixue:addRelatedSkill(maxcard_occupied_trigger)

local rfenghou_3d15j__discard_skill = fk.CreateActiveSkill{
  name = "rfenghou_3d15j__discard_skill",
  card_filter = function (self, to_select, cards, player)
    if not table.contains(player.player_cards[Player.Hand], to_select)
    or getMaxCardsOccupied(player, Fk:getCardById(to_select)) <= 0
    or player:prohibitDiscard(to_select) then return false end
    return not self:feasible({}, cards, player)
  end,
  target_filter = Util.FalseFunc,
  feasible = function (self, _, cards, player)
    local num = 0
    local discardNum = self.discardNum or 1
    for _, id in ipairs(cards) do
      num = num + getMaxCardsOccupied(player, Fk:getCardById(id))
    end
    return num >= discardNum
  end,
}
Fk:addSkill(rfenghou_3d15j__discard_skill)

Fk:loadTranslationTable{
  ["#maxcard_occupied_trigger"] = "弃牌阶段",
  ["rfenghou_3d15j__discard_skill"] = "弃牌",
  ["#rfenghou_3d15j__discard_skill"] = "请弃置 %arg 张牌",
}

zhaoe:addSkill(cuixue)
Fk:loadTranslationTable{
  ["rfenghou_3d15j__cuixue"] = "淬血",
  [":rfenghou_3d15j__cuixue"] = "锁定技，回合开始时，你令本回合【杀】伤害基数和占用手牌上限改为(0-2)，手牌上限减等量；回合结束时，你展示均为【杀】的手牌并对一名其他角色造成1点伤害。",
  ["#rfenghou_3d15j__cuixue-damage"] = "淬血：对一名其他角色造成1点伤害",
  ["@rfenghou_3d15j__cuixue-turn"] = "淬血",
  ["#rfenghou_3d15j__cuixue-choice"] = "淬血：请令本回合【杀】伤害基数和占用手牌上限改为上述一个数字！",

  ["$rfenghou_3d15j__cuixue1"] = "血债血偿、天理昭然！",
  ["$rfenghou_3d15j__cuixue2"] = "染刃尽是心头血，夙寐都作鬓间霜。",
}

local suchou = fk.CreateTriggerSkill{
  name = "rfenghou_3d15j__suchou",
  anim_type = "offensive",
  events = {fk.DamageCaused, fk.Damage, fk.Damaged},
  can_trigger = function (self, event, target, player, data)
    if not player:hasSkill(self) or target ~= player then return false end
    local mark = player:getMark("rfenghou_3d15j__suchou_tar")
    if event == fk.DamageCaused then
      return data.to.id == mark and data.damage < (data.to.hp + data.to.shield)
      and table.contains(player.player_skills, self) -- 防止虚拟技能没法删除
    elseif event == fk.Damage then
      return data.to.id == mark and player:isWounded()
    elseif event == fk.Damaged then
      mark = player.room:getPlayerById(mark)
      return mark and not mark.dead and not player:isNude()
    end
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    if event == fk.DamageCaused then
      return room:askForSkillInvoke(player, self.name, nil, "#rfenghou_3d15j__suchou-damage:"..data.to.id.."::"..((data.to.hp + data.to.shield)))
    elseif event == fk.Damage then
      return true
    else
      local cards = room:askForCard(player, 1, 999, true, self.name, true, nil, "#rfenghou_3d15j__suchou-recast")
      if #cards > 0 then
        self.cost_data = {cards = cards}
        return true
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if event == fk.DamageCaused then
      data.damage = (data.to.hp + data.to.shield)
      room:handleAddLoseSkills(player, "-"..self.name)
    elseif event == fk.Damage then
      room:recover { num = 1, skillName = self.name, who = player, recoverBy = player }
    else
      room:recastCard(self.cost_data.cards, player, self.name)
    end
  end,

  refresh_events = {fk.Damage},
  can_refresh = function (self, event, target, player, data)
    return target == player and player:hasSkill(self, true)
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    local currentDamage = room.logic:getCurrentEvent():findParent(GameEvent.Damage, true)
    if not currentDamage then return end
    local lastDamage = room.logic:getActualDamageEvents(1, function(e)
      return e.data[1].from == player and e.id < currentDamage.id
    end, nil, 1)[1]
    if lastDamage then
      local mark = player:getMark("rfenghou_3d15j__suchou_tar")
      local new = 0
      if lastDamage.data[1].to == data.to then
        new = data.to.id
      end
      if mark ~= new then
        room:doIndicate(player.id, {new})
        room:setPlayerMark(player, "rfenghou_3d15j__suchou_tar", new)
        room:setPlayerMark(player, "@rfenghou_3d15j__suchou", new == 0 and 0 or room:getPlayerById(new).general)
      end
    end
  end,

  on_lose = function (self, player, is_death)
    player.room:setPlayerMark(player, "@rfenghou_3d15j__suchou", 0)
  end,
}
zhaoe:addSkill(suchou)

Fk:loadTranslationTable{
  ["rfenghou_3d15j__suchou"] = "夙雠",
  [":rfenghou_3d15j__suchou"] = "你对一名角色连续造成：两次伤害后，回复1点体力；三次伤害时，可以将之改为致命伤害并失去此技能。若有满足前者的角色存活，你受到伤害后可以重铸任意张牌。",
  ["@rfenghou_3d15j__suchou"] = "夙雠",
  ["#rfenghou_3d15j__suchou-damage"] = "夙雠：你可以将对 %src 造成伤害改为 %arg 点，并失去“夙雠”",
  ["#rfenghou_3d15j__suchou-recast"] = "夙雠：你可以重铸任意张牌",

  ["$rfenghou_3d15j__suchou1"] = "遗身如浮烟，未雪何由安。",
  ["$rfenghou_3d15j__suchou2"] = "父母之仇，弗与共天地！",
} 

return extension